
% INPUT - Line profile raw data 
    % For exfoliated fibrils use the raw data file 'DataExf'
    % 'DataExf' file contains 17 line profile data 
    
% OUTPUT - Variable 'Exf_Dia' which contains the diameter values.
    % The code does a Gaussian fit for each line profile and calculate - 
    % the full width at half maximum (FWHM) for each Gaussian fit. This
    % FWHM value is considered as the diameter for each measurement.

for i=1:length(DataExf.x)

    x = DataExf.x{i}; % x axis data of the 'i' th line profile in nm
    y = DataExf.y{i}; % y axis data of the 'i' th line profile in nm
              


    f1 =createFit(x,y); % call fitting function to fit a Gaussian curve to data
    coef = coeffvalues(f1); % output fitting parameters as coef
    x1 = [min(x):0.1:max(x)];   % create x range to plot the fit
    Yest = gaussian(x1,coef);   % obtain y values form the fit

    % Find the half max value.
    halfMax = (min(Yest) + max(Yest)) / 2;
    % Find where the data first drops below half the max.
    index1 = find(Yest >= halfMax, 1, 'first');
    % Find where the data last rises above half the max.
    index2 = find(Yest >= halfMax, 1, 'last');

    % calculate FWHM
    FWHM = x1(index2) - x1(index1);
    
    figure;
    plot(x,y); % plot raw line profile
    hold on;
    plot(x1,Yest);  %plot Guassian fit

    hold on;
    line([x1(index1), x1(index2)], [Yest(index1), Yest(index2)], 'Color', 'r', 'LineWidth', 2);
    
    legend('Line Profile','Gaussian Fit','FWHM')

    % FWHM = Fibril diameter

    Exf_Dia(i) = FWHM; % Store diameter values in Exf_Dia variable

end

figure;
histogram(Exf_Dia);
title('Diameter distribution of exfoliated nanofibrils');
xlabel('Diameter (nm)');
ylabel('Count');
mean(Exf_Dia)
std(Exf_Dia)
